package com.example.broadcastwebsocket.handler;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NormalHandler extends TextWebSocketHandler {

    private final ExecutorService executorService = Executors.newSingleThreadExecutor();
    private PipedInputStream pipedInputStream;
    private PipedOutputStream pipedOutputStream;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
       /* pipedInputStream = new PipedInputStream();
        pipedOutputStream = new PipedOutputStream(pipedInputStream);

        executorService.submit(() -> {
            System.out.println("11111111111111");
            try {
                ProcessBuilder processBuilder = new ProcessBuilder(
                        "ffmpeg", "-i", "-", "-c:v", "libx264", "-c:a", "aac", "-f", "flv", "rtmp://124.70.49.99/live/stream"
                );
                Process process = processBuilder.start();
                OutputStream ffmpegInput = process.getOutputStream();

                byte[] buffer = new byte[1024];
                int length;
                while ((length = pipedInputStream.read(buffer)) != -1) {
                    ffmpegInput.write(buffer, 0, length);
                }
                ffmpegInput.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });*/
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        session.sendMessage(new TextMessage("您好！"));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (pipedInputStream != null) {
            pipedInputStream.close();
        }
        if (pipedOutputStream != null) {
            pipedOutputStream.close();
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        if (pipedInputStream != null) {
            pipedInputStream.close();
        }
        if (pipedOutputStream != null) {
            pipedOutputStream.close();
        }
        executorService.shutdown();
    }
}